<template>
  <section :id="id" class="doughnut-chart"></section>
</template>

<script>
  import echarts from 'echarts'
  import util from '@/libs/util'

  export default {
    name: 'DoughnutChart',
    props: {
      data: {
        type: Array,
        default: () => {
          return [{name: 'test', value: 100}]
        }
      }
    },
    watch: {
      data: {
        handler(value) {
          this.init(this.data)
        },
        deep: true
      }
    },
    data() {
      return {
        id: 'DoughnutChart' + Math.random() * 100000000,
        chart: null
      }
    },
    mounted() {
      this.init(this.data)
    },
    methods: {
      init(data) {
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}<br>({d}%)',
            textStyle: {
              fontSize: util.fontSize(0.22)
            }
          },
          color: ['#2668E6', '#30DFBB', '#FFDB40', '#FFA74E', '#F9496A', '#D1368D'],
          legend: {
            show: true,
            // orient: 'horizontal',
            // align: 'left',
            icon: 'circle',
            x: 'center',
            y: 'bottom',
            itemWidth: util.fontSize(0.15),
            itemHeight: util.fontSize(0.15),
            itemGap: 15,
            // itemGap: util.fontSize(0.25),
            textStyle: { // 图例文字的样式
              color: '#fff',
              fontSize: util.fontSize(0.24)
            },
            data: data
            // formatter: function(name) {
            //   let target
            //   for (let i = 0, l = data.length; i < l; i++) {
            //     if (data[i].name === name) {
            //       target = data[i].value
            //     }
            //   }
            //   return name + '   ' + target + '宗'
            // }

          },
          series: [{
            name: '数量',
            type: 'pie',
            radius: ['45%', '60%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            label: {
              normal: {
                show: true,
                // formatter: [
                //   '{a|{b}}',
                //   '{c|{d}%}'
                // ].join('\n'),
                // formatter: '{a|{b}}',
                formatter: '{a|{c}次}，{a|{d}%}',
                rich: {
                  a: {
                    fontSize: util.fontSize(0.26),
                    height: util.fontSize(0.26)
                  }
                }
              }
            },
            labelLine: {
              normal: {
                show: true
              }
            },
            data: data
          }]
        }
        if (this.chart === null) {
          this.chart = echarts.init(document.getElementById(this.id))
        }
        this.chart.setOption(option)
      }
    }
  }
</script>

<style scoped>
.doughnut-chart {
  width: 100%;
  height: 100%;
}
</style>
